package com.prim.threadcoreknowledge.stopthread.volatiledemo;

import java.util.Arrays;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

/**
 * volatile 的局限:陷入阻塞时，volatile是无法停止线程的
 * 此例中进行演示:生产者的生产速度很快，而消费者消费速度很慢
 * 所以阻塞队列满了以后，生产者会阻塞，等待消费者进一步消费
 */
public class WrongWayVolatileCantStop {

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue storage = new ArrayBlockingQueue(10);
        Producer producer = new Producer(storage);
        Thread thread = new Thread(producer);
        thread.start();
        //塞满这个队列
        Thread.sleep(1000);

        Consumer consumer = new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(storage.take() + "被消费了");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要更多数据了");
        //消费者不需要数据了，让生产者停止下来 但实际情况生产者并没有停止
        producer.canceled = true;
        //错误原因 一旦线程被长时间阻塞就没有办法去停止线程了，不能唤醒线程 一直等待put()的方法
        //所以interrupt方法即便线程长时间阻塞，interrupt可以即使响应的。
    }

}

class Producer implements Runnable {
    public volatile boolean canceled = false;
    private BlockingQueue storage;

    public Producer(BlockingQueue storge) {
        this.storage = storge;
    }

    @Override
    public void run() {
        int num = 0;
        try {
            while (num <= 100000 && !canceled) {
                if (num % 100 == 0) {
                    storage.put(num);
                    System.out.println(num + "是100倍数 放到仓库中");
                }
                num++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者停止运行");
        }
    }
}

class Consumer {
    private BlockingQueue storage;

    public Consumer(BlockingQueue storage) {
        this.storage = storage;
    }

    public boolean needMoreNums() {
        if (Math.random() > 0.95) {
            return false;
        }
        return true;
    }
}
